package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.domain.BaiduIpLocation;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.util.UriUtils;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URLConnection;
import java.util.LinkedHashMap;
import java.util.Map;
import java.net.URL;


@Slf4j
@RestController
@RequestMapping("/map/ip")
public class BaiduMapController extends BaseController {

    private static final String URL = "https://api.map.baidu.com/location/ip?";
    private static final String AK = "7tGt8xHp3Suk5SdR8o2hVlsyj9yjyuQh";
    private final ObjectMapper objectMapper = new ObjectMapper();

    @GetMapping("/location")
    public AjaxResult getIpLocation(String ip) {
        try {
            Map<String, String> params = new LinkedHashMap<>();
            params.put("ip", ip == null ? "" : ip);
            params.put("coor", "bd09ll");
            params.put("ak", AK);

            String jsonResponse = requestGetAK(URL, params);
            BaiduIpLocation location = objectMapper.readValue(jsonResponse, BaiduIpLocation.class);

            if (location.getStatus() != 0) {
                return AjaxResult.error("定位失败: " + location.getMessage());
            }

            return AjaxResult.success("获取位置成功", location.getContent());
        } catch (Exception e) {
            return AjaxResult.error("获取位置信息失败: " + e.getMessage());
        }
    }

    private String requestGetAK(String strUrl, Map<String, String> param) throws Exception {

        if (strUrl == null || strUrl.length() <= 0 || param == null || param.size() <= 0) {
            return "";
        }

        StringBuffer queryString = new StringBuffer();
        queryString.append(strUrl);
        for (Map.Entry<?, ?> pair : param.entrySet()) {
            queryString.append(pair.getKey() + "=");
            queryString.append(UriUtils.encode((String) pair.getValue(), "UTF-8") + "&");
        }

        if (queryString.length() > 0) {
            queryString.deleteCharAt(queryString.length() - 1);
        }

        java.net.URL url = new URL(queryString.toString());
        URLConnection httpConnection = (HttpURLConnection) url.openConnection();
        httpConnection.connect();

        InputStreamReader isr = new InputStreamReader(httpConnection.getInputStream());
        BufferedReader reader = new BufferedReader(isr);
        StringBuffer buffer = new StringBuffer();
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }
        reader.close();
        isr.close();

        return buffer.toString();
    }
}